<template>
    <div class="order-management">
      <h1>订单管理</h1>
      
      <el-card>
        <template #header>
          <div class="card-header">
            <div class="filter-area">
              <el-input
                v-model="searchQuery"
                placeholder="搜索订单（ID/用户/车辆）"
                class="search-input"
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><search /></el-icon>
                </template>
              </el-input>
              
              <el-select v-model="statusFilter" placeholder="订单状态" clearable class="filter-item">
                <el-option label="全部订单" value="" />
                <el-option label="进行中" value="0" />
                <el-option label="已完成" value="1" />
                <el-option label="已取消" value="2" />
              </el-select>
            </div>
          </div>
        </template>
        
        <el-table
          :data="filteredOrders"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="订单ID" width="80" />
          <el-table-column prop="userId" label="用户ID" width="80" />
          <el-table-column prop="vehicleId" label="车辆ID" width="80" />
          <el-table-column prop="startTime" label="开始时间" width="180" />
          <el-table-column prop="endTime" label="结束时间" width="180" />
          <el-table-column prop="startShopId" label="取车门店" width="100" />
          <el-table-column prop="endShopId" label="还车门店" width="100" />
          <el-table-column prop="totalPrice" label="总价" width="100">
            <template #default="scope">
              ¥{{ scope.row.totalPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag 
                :type="scope.row.status === 0 ? 'warning' : scope.row.status === 1 ? 'success' : 'info'">
                {{ scope.row.status === 0 ? '进行中' : scope.row.status === 1 ? '已完成' : '已取消' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleViewDetails(scope.row)"
              >
                详情
              </el-button>
              <el-button 
                v-if="scope.row.status === 0"
                type="success" 
                size="small" 
                @click="handleUpdateStatus(scope.row.id, 'completed')"
              >
                完成
              </el-button>
              <el-button 
                v-if="scope.row.status === 0"
                type="info" 
                size="small" 
                @click="handleUpdateStatus(scope.row.id, 'cancelled')"
              >
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 订单详情对话框 -->
      <el-dialog
        v-model="detailsDialogVisible"
        title="订单详情"
        width="800px"
      >
        <div v-if="orderDetails">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单ID">{{ orderDetails.id }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag 
                :type="orderDetails.status === 0 ? 'warning' : orderDetails.status === 1 ? 'success' : 'info'">
                {{ orderDetails.status === 0 ? '进行中' : orderDetails.status === 1 ? '已完成' : '已取消' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ orderDetails.userId }}</el-descriptions-item>
            <el-descriptions-item label="车辆ID">{{ orderDetails.vehicleId }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ orderDetails.startTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ orderDetails.endTime }}</el-descriptions-item>
            <el-descriptions-item label="取车门店">{{ orderDetails.startShopId }}</el-descriptions-item>
            <el-descriptions-item label="还车门店">{{ orderDetails.endShopId }}</el-descriptions-item>
            <el-descriptions-item label="总价">¥{{ orderDetails.totalPrice }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ orderDetails.createTime }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="actions-bar" v-if="orderDetails.status === 0">
            <el-button type="success" @click="handleUpdateStatus(orderDetails.id, 'completed')">完成订单</el-button>
            <el-button type="info" @click="handleUpdateStatus(orderDetails.id, 'cancelled')">取消订单</el-button>
          </div>
        </div>
      </el-dialog>
      
      <!-- 状态更新确认对话框 -->
      <el-dialog
        v-model="statusDialogVisible"
        :title="statusAction === 'completed' ? '确认完成订单' : '确认取消订单'"
        width="300px"
      >
        <div class="confirm-text">
          确定要将订单状态更改为<span class="status-text">{{ statusAction === 'completed' ? '已完成' : '已取消' }}</span>吗？
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="statusDialogVisible = false">取消</el-button>
            <el-button 
              :type="statusAction === 'completed' ? 'success' : 'info'" 
              @click="confirmStatusUpdate"
            >
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, onMounted, computed, watch } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  
  export default {
    name: 'OrderManagement',
    components: {
      Search
    },
    setup() {
      const loading = ref(false)
      const orders = ref([])
      const searchQuery = ref('')
      const statusFilter = ref('')
      const detailsDialogVisible = ref(false)
      const statusDialogVisible = ref(false)
      const orderDetails = ref(null)
      const statusAction = ref('')
      const statusUpdateOrderId = ref(null)
      
      const filteredOrders = computed(() => {
        let result = orders.value
        
        // Filter by status if selected
        if (statusFilter.value) {
          result = result.filter(order => order.status.toString() === statusFilter.value)
        }
        
        // Filter by search query
        if (searchQuery.value) {
          const query = searchQuery.value.toLowerCase()
          result = result.filter(order => 
            order.id.toString().includes(query) ||
            order.userId.toString().includes(query) ||
            order.vehicleId.toString().includes(query)
          )
        }
        
        return result
      })
      
      const fetchOrders = async () => {
        loading.value = true
        try {
          const res = await axios.get('/api/admin/orders')
          if (res.data.success) {
            orders.value = res.data.data
          }
        } catch (error) {
          console.error('获取订单列表失败:', error)
          ElMessage.error('获取订单列表失败')
        } finally {
          loading.value = false
        }
      }
      
      const handleSearch = () => {
        // 搜索功能通过computed属性filteredOrders自动实现
      }
      
      const handleViewDetails = async (row) => {
        try {
          const res = await axios.get(`/api/admin/orders/${row.id}`)
          if (res.data.success) {
            orderDetails.value = res.data.data
            detailsDialogVisible.value = true
          }
        } catch (error) {
          console.error('获取订单详情失败:', error)
          ElMessage.error('获取订单详情失败')
        }
      }
      
      const handleUpdateStatus = (orderId, action) => {
        statusUpdateOrderId.value = orderId
        statusAction.value = action
        statusDialogVisible.value = true
      }
      
      const confirmStatusUpdate = async () => {
        if (!statusUpdateOrderId.value || !statusAction.value) return
        
        try {
          const res = await axios.put(`/api/admin/orders/${statusUpdateOrderId.value}/status`, null, {
            params: { status: statusAction.value }
          })
          
          if (res.data.success) {
            ElMessage.success(`订单状态已更新为${statusAction.value === 'completed' ? '已完成' : '已取消'}`)
            fetchOrders()
            statusDialogVisible.value = false
            detailsDialogVisible.value = false
          } else {
            ElMessage.error(res.data.message || '操作失败')
          }
        } catch (error) {
          console.error('更新订单状态失败:', error)
          ElMessage.error('更新订单状态失败')
        }
      }
      
      onMounted(() => {
        fetchOrders()
      })
      
      // Refresh order details when orders are updated
      watch(orders, () => {
        if (orderDetails.value && orderDetails.value.id) {
          const updatedOrder = orders.value.find(o => o.id === orderDetails.value.id)
          if (updatedOrder) {
            orderDetails.value = updatedOrder
          }
        }
      })
      
      return {
        loading,
        orders,
        filteredOrders,
        searchQuery,
        statusFilter,
        detailsDialogVisible,
        statusDialogVisible,
        orderDetails,
        statusAction,
        handleSearch,
        handleViewDetails,
        handleUpdateStatus,
        confirmStatusUpdate
      }
    }
  }
  </script>
  
  <style scoped>
  .order-management {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .filter-area {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .search-input {
    width: 300px;
  }
  
  .filter-item {
    width: 150px;
  }
  
  .actions-bar {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 20px;
  }
  
  .confirm-text {
    text-align: center;
    margin: 20px 0;
  }
  
  .status-text {
    font-weight: bold;
    margin: 0 5px;
  }
  </style>